
* the GMM code makes a ridiculous number of variables
clear
clear matrix
clear mata
set maxvar 120000
set matsize 4000

* 0: no 1: compare numerical and analytic derivs
local check_deriv 0

* 0: don't add extra column for fwdarb dropping basis regressor
local runexbasis 0

local ptol = 10^(-6)
local vtol = 10^(-20)
local opts conv_maxiter(40) conv_ptol(`ptol') conv_vtol(`vtol') 
//tracelevel("step")


local setype hac nwest 12
local qtrsetype hac nwest 4
local basissetype hac nwest 12
//local setype cluster Date

//conv_maxiter(120) technique(bfgs 10 nr 10)
//technique(bfgs)



//US Sov FX FF Commod Onew90 CDS fwdarb
//SmallUS SmallFX SmallOn90 SmallCD SmallSv SmallComm SmallFF
//


local vars_dhw int_value pc1ret //table 8

local vars_dhwpre2019 int_value pc1ret //new table A14 for pre-2019

local vars_hkm Mkt hkm_factor //table A15

local vars_dhw3i Mkt int_value pc1ret //table A19

local vars_hkmi int_value //table A20

local vars_hkm2i Mkt int_value //table A16

local vars_dhw3 Mkt hkm_factor pc1ret //table A21

local vars_dhwold int_value basis_shock //new table A23 (old specification)

local vars_dhwBRF int_value pc1ret lag_basis //table A22

local vars_dhwUSD int_value basis_JPYUSD //table A24

local vars_dhw3v3 int_value basis_3v3 //table A25

local vars_dhwtop5 int_value basis_top5 //table A26

local vars_dhwtop6 int_value basis_top6 //table A27

local vars_commonsample int_value pc1ret //table A28

local vars_dhwpc int_value pc1shock //table A30

local vars_dhwar1 int_value basis_ar1 //table A29

local vars_dhw2 Mkt pc1ret //table A18

local vars_dhw1 pc1ret 

local vars_dhwquarter int_value pc1ret //
local vars_dhwhkmquarter hkm_factor pc1ret
local vars_dhwaemquarter aem_new pc1ret

//local vars_aemquarter aem_new
local vars_aemmktquarter Mkt aem //table A17
local vars_hkmmktquarter Mkt hkm_factor 

local vars_aemmktpre2019quarter Mkt aem
local vars_hkmmktpre2019quarter Mkt hkm_factor 

local vars_hkmpre2013 Mkt hkm_factor 
local vars_intpre2013 int_value


if $run_quarter == 1 {

	local var_list vars_aemmktquarter
	local allruns Allbasisnewsmallex
	
	local labels US Sov FX FF6 CDS SmallOpt SmallCmNew  

	local labelstorun US Sov FX SmallOpt  CDS FF6 SmallCmNew 
}
else {
	local var_list vars_hkm vars_dhw3i vars_dhw2 vars_dhw vars_dhwpre2019 vars_hkmi vars_hkm2i vars_dhw3 vars_dhwold vars_dhwBRF vars_dhwUSD vars_dhw3v3 vars_dhwtop5 vars_dhwtop6 vars_commonsample vars_dhwpc vars_dhwar1  

	local allruns Allbasisnewsmall
	
	local labels US Sov FX SmallOpt fwdarb CDS FF6 SmallCmNew  

	local labelstorun US Sov FX SmallOpt fwdarb CDS FF6 SmallCmNew 
}






//commodities have essentially no spread in betas
local Allex US Sov FX Onew90 CDS

local Allbasis US Sov FX Onew100 CDS fwdarb


local Allbasisnewsmall US Sov FX SmallOpt CDS fwdarb FF6 SmallCmNew 

local Allbasisnewsmallex US Sov FX SmallOpt CDS FF6 SmallCmNew

local Allbasisnew US Sov FX Onew100 CDS fwdarb FF6 Commod

local AllComm US FX Onew90 fwdarb

local AllUS US FX Onew90

local Allsmallex SmallU SmallF SmallOn90

local Allsmall SmallUS SmallSv SmallFX SmallComm SmallOn90 SmallCD SmallFF

local Alltest Sov fwdarb

local Allex_mtitle "US/Sov/FX/Opt/CDS"

local Allbasisnew_mtitle "1-8"

local Allbasisnewsmall_mtitle "1-8"

local Allbasisnewsmallex_mtitle "1-7"

local Allbasis_mtitle "1-6"

local AllComm_mtitle "US/FX/Opt/FA"

local AllUS_mtitle "US/FX/Opt"

local Alltest_mtitle "Sov/FA"

local Allsmall_mtitle "All"
local Allsmallex_mtitle "Sm US/FX/Opt"





eststo clear

local cons_labels
foreach lbl in `labels' {
	local cons_labels `cons_labels' lambda_`lbl':_cons "`lbl' Constant"
}

use "./OutputInterim/CrossSectionData.dta", clear

rename basis_shock bshock
rename basisresid_shock brshock
rename basis_ar1 bar1
foreach lbl in `labels' { 
	rename eret_`lbl'* `lbl'*
	ds `lbl'*
	local `lbl'_assets = r(varlist)
	rename `lbl'* eret_`lbl'* 
}
rename bshock basis_shock
rename brshock basisresid_shock
rename bar1 basis_ar1


tempfile temp

foreach varl in `var_list' {

	if regexm("`varl'","quarter") {
		use "./OutputInterim/CrossSectionDataQtr.dta", clear
		
		local oldsetype `setype'
		local setype `qtrsetype'
		
		disp "`setype', `oldsetype'"
	}
	else {
		use "./OutputInterim/CrossSectionData.dta", clear
	}

	//doesn't work on quarter panel, but never run quarter pre-2019
	if regexm("`varl'","pre2019") {
		if regexm("`varl'","quarter") {
			drop if Date > yq(2019,4)
		}
		else {
			drop if Date > ym(2019,12)
		}
	}
	if regexm("`varl'","pre2013") {
		if regexm("`varl'","quarter") {
			drop if Date > yq(2011,4)
		}
		else {
			drop if Date > ym(2011,12)
		}
	}
	

	local varsall ``varl''
	
	disp "vars: `varsall'"
	
	local nparams = 0
	local nparamsexbasis = 0
	local nlagvars = 0
	local varsexbasis
	
	//local testcmd
	//local testcmd2
	
	local testcmd_new
	local testcmd2_new
	
	local atvars
	local atvarsex
	
	local lagvars
	local vars
	
	foreach v in `varsall' {
		local nparams = `nparams' + 1
		
		local atvars `atvars' @`v'
		
		if ~regexm("`v'","basis") & ~regexm("`v'","lag") {
			local nparamsexbasis = `nparamsexbasis' + 1
			local varsexbasis `varsexbasis' `v'
			local atvarsex `atvarsex' @`v'
		}
		
		if ~regexm("`v'","hkm") & ~regexm("`v'","pc1shock") & ~regexm("`v'","basis_ar1") & ~regexm("`v'","xccy") & ~regexm("`v'","lag") & ~regexm("`v'","aem"){
			//local testcmd `testcmd' ([lambda]`v' = ``v'_mean')
			local testcmd_new `testcmd_new' ([lambda]`v' = [means]`v')
			if ~regexm("`v'","basis") {
				//local testcmd2 `testcmd2' ([lambda]`v' = ``v'_mean')
				local testcmd2_new `testcmd2_new' ([lambda]`v' = [means]`v')
			}
		}
		
		if regexm("`v'","lag") {
			local nlagvars = `nlagvars' + 1
			local lagvars `lagvars' `v'
		}
		else {
			local vars `vars' `v'
		}
	}
	
	local nparams = `nparams' - `nlagvars'
	
	local comsample nocommonesample
	
	if regexm("`varl'","commonsample") {
		local comsample 
	}
	
	disp "np: `nparams' npex: `nparamsexbasis'"

	matrix var_means = J(1,`nparams',0)
	
	if `nparamsexbasis' > 0 {
		matrix var_means_ex = J(1,`nparamsexbasis',0)
	}
	else {
		matrix var_means_ex = J(1,1,0)
	}
	
	local j = 0
	local jex = 0
	foreach v in `vars' {
		local j = `j'+1
		matrix accum ignore = `v', means(var_means_`v') noconstant
		matrix var_means[1,`j'] = var_means_`v'[1,1]
		if ~regexm("`v'","basis") {
			local jex = `jex'+1
			matrix var_means_ex[1,`jex'] = var_means_`v'[1,1]
		}
	}
	matrix list var_means
	matrix list var_means_ex
	
	corr `vars', covariance
	matrix cmat = r(C)
	matrix vars_vars = vecdiag(invsym(diag(vecdiag(cmat))))
	
	if `nparamsexbasis' > 0 {
	
		matrix accum ignore = `varsexbasis', means(varex_means) noconstant
		corr `varsexbasis', covariance
		matrix cmat = r(C)
		matrix varsex_vars = vecdiag(invsym(cmat))
	}
	
	local estnames
	local estnames2
	local estnames_one
	local estnames_two
	local estnames2_one
	local estnames2_two
	
	local mtitles
	local mtitles2
	
	local run_assets
	local run_labels
	
	foreach lbl in `labels' { 
	
		disp "Running `lbl'"
	
		local `lbl'_params 
		local `lbl'_insteqs
		local `lbl'_erets
		
		local `lbl'_priceerrors 0
		
		local nassets_`lbl' = 0
	
		foreach asset in ``lbl'_assets' {
		
			local nassets_`lbl' = `nassets_`lbl'' + 1
			
			local `lbl'_params  ``lbl'_params' {`asset': `vars' `lagvars' _cons}
			local `lbl'_insteqs ``lbl'_insteqs' `nassets_`lbl''
			local `lbl'_erets ``lbl'_erets' eret_`asset'
			
			local price_error_`asset' _b[means:eret_`asset'] 
			foreach v in `vars' {
				local price_error_`asset' `price_error_`asset'' - _b[lambda:`v']*_b[`asset':`v']
			}
			local price_error_`asset' `price_error_`asset'' - _b[lambda`lbl':_cons]
		
			local `lbl'_priceerrors ``lbl'_priceerrors' + abs(`price_error_`asset'')
			
		
		}
		local nassets = `nassets_`lbl''
		
		matrix `lbl'_mrets = J(1,`nassets',0)
		local j = 0
		foreach asset in ``lbl'_assets' {
			local j = `j' + 1
			quietly matrix accum ignore = eret_`asset', means(`lbl'_mret_`asset') noconstant
			matrix `lbl'_mrets[1,`j'] = `lbl'_mret_`asset'[1,1]
			matrix drop `lbl'_mret_`asset'
		}
		matrix colnames `lbl'_mrets = ``lbl'_erets'
		//matrix list `lbl'_mrets
		
		quietly corr ``lbl'_erets', covariance
		matrix cmat = r(C)
		
		matrix ret_vars_`lbl' = J(1,`nassets',1 / (trace(cmat) / `nassets') / `nassets')
		matrix colnames ret_vars_`lbl' = ``lbl'_erets'
		
		//matrix ret_vars_`lbl' = vecdiag(invsym(diag(vecdiag(cmat)))) / `nassets'
	
		quietly gmm gmm_ols, onestep vce(robust) instruments(`vars' `lagvars') factors(`vars') assets(``lbl'_assets') assetclasses(`lbl') parameters(``lbl'_params') nequations(`nassets') return_prefix(eret_) winitial(identity) `comsample' hasderivatives rfvars(`lagvars')
		
		matrix `lbl'_betas = e(b)
		
	}
	
	foreach lbl in `labelstorun' { 
			local nassets = `nassets_`lbl''
			
			local run_labels `run_labels'_`lbl'
			local run_assets `run_assets' ``lbl'_erets'
			
			save `temp', replace
			clear
			
			
			svmat `lbl'_betas, names(eqcol)
			svmat `lbl'_mrets, names(eqcol)
			gen n = _n
			drop *_cons
			reshape long `atvars' _eret_, i(n) string
			
			reg _eret_ `vars'
			
			matrix `lbl'_lambdainit = e(b)
			
			matrix `lbl'_froms = `lbl'_betas, `lbl'_mrets, var_means, `lbl'_lambdainit
			
			//perturbing this helps convergence/divide by zero errors
			if regexm("`varl''","aem") & regexm("`lbl'","US") {
				matrix `lbl'_lambdainit2 = J(1,`nparams' + 1,0)	
				matrix `lbl'_mrets2 = J(1,`nassets',0)	
				matrix `lbl'_betas2 = J(1,`nassets'*(`nparams'+1),0)	
				matrix var_means2 = J(1,`nparams',0)
				matrix `lbl'_froms = `lbl'_betas2, `lbl'_mrets2, var_means2, `lbl'_lambdainit2
			}
			
			use `temp', clear
				
						
				
			local numeq = 2*`nassets' + 2*`nparams' + 1
			
			/*disp "`lbl' `vars'"
			disp "``lbl'_insteqs'"
			disp "``lbl'_assets'"
			disp "``lbl'_erets'"
			disp "``lbl'_params'"*/
			
			gmm gmm_ols, onestep vce(`setype') instruments(``lbl'_insteqs': `vars' `lagvars') factors(`vars') assets(``lbl'_assets') assetclasses(`lbl') parameters(``lbl'_params' {means: ``lbl'_erets' `vars'} {lambda: `vars'} {lambda`lbl': _cons}) nequations(`numeq') return_prefix(eret_) winitial(identity) from(`lbl'_froms) `comsample'  hasderivatives `opts' rfvars(`lagvars')
			
			
			if `check_deriv' == 1 {
			
				matrix list `lbl'_betas
				matrix list `lbl'_mrets
			
				matrix temp = e(G)
			
				gmm gmm_ols, onestep vce(`setype') instruments(``lbl'_insteqs': `vars' `lagvars') factors(`vars') assets(``lbl'_assets') assetclasses(`lbl') parameters(``lbl'_params' {means: ``lbl'_erets' `vars'} {lambda: `vars'} {lambda`lbl': _cons}) nequations(`numeq') return_prefix(eret_) winitial(identity) from(`lbl'_froms) `comsample'  `opts' rfvars(`lagvars')

				matrix temp2 = temp - e(G)
				matrix list temp2
			}
			
			local `lbl'_mape = (``lbl'_priceerrors') / `nassets'
			
			if "`comsample'" == "nocommonesample" {
				matrix temp = e(N_byequation)
				local betaN = temp[1,1]
				local meanN = temp[1,`nassets'+1]
			
				estadd scalar betaN = `betaN'
				estadd scalar meanN = `meanN'
			}
			else {
				estadd scalar betaN = e(N)
				estadd scalar meanN = e(N)
			}
			
			estadd scalar Nassets = `nassets'
			
			estadd scalar MAPE = ``lbl'_mape'
			
			
			
			
			
			//test `testcmd'
			//estadd scalar PriceTest = r(p)
			
			test `testcmd_new'
			estadd scalar PriceTestNew = r(p)
		
			eststo `lbl'_xs
			local estnames `estnames' `lbl'_xs 
			
			if ~regexm("`lbl'","fwdarb") & ~regexm("`lbl'","ibor")  {
				if ~regexm("`lbl'","Onew90") {
					local mtitles `mtitles' `lbl'
				}
				else {
					local mtitles `mtitles' Opt
				}
			}
			else {
				local mtitles `mtitles' FwdArb
			}
			
		
	}
	
	outsheet `vars' `run_assets' using "./OutputInterim/MatlabInput/`varl'`run_labels'.csv", comma replace
	
	shell $matlab -nosplash -nodesktop -r "filename='`varl'`run_labels'.csv'; multi=0; run ./MatlabCode/KZRankTest"
	
	save `temp', replace
	
	insheet using "./OutputInterim/MatlabInput/output_`varl'`run_labels'.csv", clear names
	
	foreach lbl in `labelstorun' {
		su pvals if names == "`lbl'", meanonly
		
		estadd scalar KZpval = r(mean) : `lbl'_xs 
	}
	
	use `temp', clear
	
	if `nparamsexbasis' < `nparams' & `nparamsexbasis' > 0 & `runexbasis' > 0 {
	
		foreach lbl in fwdarb { 
	
			local exbasis_params 
			local exbasis_insteqs
			local exbasis_erets
			
			local nassets = 0
			
			local exbasis_priceerrors 0
			
			foreach asset in ``lbl'_assets' {
			
				local nassets = `nassets' + 1
				
				local exbasis_params  `exbasis_params' {`asset': `varsexbasis' `lagvars' _cons}
				local exbasis_insteqs `exbasis_insteqs' `nassets'
				local exbasis_erets `exbasis_erets' eret_`asset'
				
				local price_error_`asset' _b[means:eret_`asset'] 
				foreach v in `varsexbasis' {
					local price_error_`asset' `price_error_`asset'' - _b[lambda:`v']*_b[`asset':`v']
				}
				local price_error_`asset' `price_error_`asset'' - _b[lambda`lbl':_cons]
			
				local exbasis_priceerrors `exbasis_priceerrors' + abs(`price_error_`asset'')
			
			}
			

		
			quietly gmm gmm_ols, onestep vce(robust) instruments(`varsexbasis' `lagvars') factors(`varsexbasis') assets(``lbl'_assets') assetclasses(`lbl') parameters(`exbasis_params') nequations(`nassets') return_prefix(eret_) winitial(identity) `comsample' hasderivatives rfvars(`lagvars')
			
			//matrix accum ignore = `exbasis_erets', means(exbasis_mrets) noconstant
	
			local numeq = 2*`nassets' + 2*`nparamsexbasis' + 1
				
				
			save `temp', replace
			clear
			
			matrix `lbl'_betasex = e(b)
			svmat `lbl'_betasex, names(eqcol)
			svmat `lbl'_mrets, names(eqcol)
			gen n = _n
			drop *_cons
			reshape long `atvarsex' _eret_, i(n) string
			
			reg _eret_ `varsexbasis'
			
			matrix `lbl'_lambdainit = e(b)	
				
			matrix exbasis_froms = `lbl'_betasex, `lbl'_mrets, var_means_ex, `lbl'_lambdainit 
			use `temp', clear
			
			gmm gmm_ols, onestep vce(`basissetype') instruments(`exbasis_insteqs': `varsexbasis' `lagvars') factors(`varsexbasis') assets(``lbl'_assets') assetclasses(`lbl') parameters(`exbasis_params' {means: `exbasis_erets' `varsexbasis'} {lambda: `varsexbasis'} {lambda`lbl': _cons}) nequations(`numeq') return_prefix(eret_) winitial(identity) from(exbasis_froms) `comsample' hasderivatives `opts' rfvars(`lagvars')
			
			
			if "`comsample'" == "nocommonesample" {
				matrix temp = e(N_byequation)
				local betaN = temp[1,1]
				local meanN = temp[1,`nassets'+1]
			
				estadd scalar betaN = `betaN'
				estadd scalar meanN = `meanN'
			}
			else {
				estadd scalar betaN = e(N)
				estadd scalar meanN = e(N)
			}
			
			estadd scalar Nassets = `nassets'
			
			local exbasis_mape = (`exbasis_priceerrors') / `nassets'
			
			estadd scalar MAPE = `exbasis_mape'

			//test `testcmd2'
			//estadd scalar PriceTest = r(p)
			
			test `testcmd2_new'
			estadd scalar PriceTestNew = r(p)
			
			eststo ex`lbl'_xs
			
			
			
			local estnames2 `estnames2' ex`lbl'_xs 
			if regexm("`lbl'","fwdarb") {
				local mtitles2 `mtitles2' FwdArb
			}
			else {
				local mtitles2 `mtitles2' IBOR-FA
			}
		
			outsheet `varsexbasis' `exbasis_erets' using "./OutputInterim/MatlabInput/`varl'ex_`lbl'.csv", comma replace
	
			shell $matlab -nosplash -nodesktop -r "filename='`varl'ex_`lbl'.csv'; multi=0; run ./MatlabCode/KZRankTest"
	
			save `temp', replace
	
			insheet using "./OutputInterim/MatlabInput/output_`varl'ex_`lbl'.csv", clear names
	
			su pvals if names == "`lbl'", meanonly
			estadd scalar KZpval = r(mean) : ex`lbl'_xs 
			
			use `temp', clear
		
		}
	}
	
	//quarter allruns fail due to N > T
	if ~regexm("`varl'","quarter") | ~regexm("`varsall'","pc1") {
	foreach allrun in `allruns' {
	
		disp "`allrun'"
		local runlabels ``allrun''
	
		disp "`runlabels'"
		
		local nlabels = 0
		local alln = 0
		
		local all_params
		local all_erets
		local all_insteqs
		local all_cons
		local allr_assets
		
		local all_mrets
		
		local all_priceerrors 0
		
		local all_weights
		local all_weights_v
		
		local all_retvars
		
		local lbl_list
		
		foreach lbl in `runlabels' {
		
			local lbl_list `lbl_list'_`lbl'
			
			local nlabels = `nlabels' + 1
			
			local all_params  `all_params' ``lbl'_params'
			
			local all_erets `all_erets' ``lbl'_erets'
			
			local all_cons `all_cons' {lambda`lbl': _cons}
			
			local nassets = 0
			
			foreach asset in ``lbl'_assets' {
				local nassets = `nassets' + 1
				local alln = `alln' + 1
				local all_insteqs `all_insteqs' `alln'
				local allr_assets `allr_assets' `asset'
			}
			
			local all_mrets `all_mrets' `lbl'_mrets,
			
			local all_priceerrors `all_priceerrors' + ``lbl'_priceerrors'
		
			//if ~regexm("`lbl'","Commod") {
				local all_weights `all_weights' J(1,`nassets',1/`nassets'),
				local all_weights_v `all_weights_v' J(1,`nassets'*(`nparams'+1),1/`nassets'),
			/*}
			else {
				local all_weights `all_weights' J(1,`nassets',1/100000),
				local all_weights_v `all_weights_v' J(1,`nassets'*(`nparams'+1),1/100000),
			}*/
			
			local all_retvars `all_retvars' ret_vars_`lbl',
		}
		
		//this combination fails for too many derivatives
		//if ~regexm("`allrun'","Allall")) {
		
		//quietly gmm gmm_ols, onestep vce(robust) instruments(`vars') factors(`vars') assets(`allr_assets') assetclasses(`runlabels') parameters(`all_params') nequations(`alln') return_prefix(eret_) winitial(identity) `comsample' hasderivatives
	
	
		disp "all_mrets: `all_mrets'"
	
		//matrix accum ignore = `all_erets', means(mrets) noconstant
		disp "all weights: `all_weights'"
		
		matrix wols2 = `all_weights' J(1,1,0)
		
		matrix wols = wols2[1,1..`alln']
		matrix wols1 = J(1,`alln',1)
		matrix colnames wols = `allr_assets'
		matrix colnames wols1 = `allr_assets'
		
		matrix all_weights = `all_weights_v' `all_weights' J(1,1,0)
		//matrix list all_weights
		matrix all_winit = diag(all_weights[1,1..`alln'*(`nparams'+2)])
		//matrix list all_winit
		
		
		//matrix all_froms = e(b), J(1,`alln',0), J(1,`nparams'+`nlabels',0)
		
		local numeq = 2*`alln' + 2*`nparams' + `nlabels'
	
	
		save `temp', replace
		clear
			
		matrix `allrun'_betas = e(b)
		local allbetas
		local allweights3
		foreach lbl in `runlabels' {
			local allbetas `allbetas' `lbl'_betas,
			svmat `lbl'_betas, names(eqcol)
			svmat `lbl'_mrets, names(eqcol)
			matrix wts = ret_vars_`lbl'
			svmat wts, names(matcol)
			local allweights3 `allweights3' ret_vars_`lbl',
		}

		matrix wols4 = `allweights3' J(1,1,0)
		matrix wols3 = wols4[1,1..`alln']
		matrix colnames wols3 = `allr_assets'
		
		gen n = _n
		drop *_cons
		reshape long `atvars' _eret_ wtseret_, i(n) j(asset) string 
		
		foreach lbl in `runlabels' {
			gen cons_`lbl' = regexm(asset,"`lbl'")
		}
		
		reg _eret_ `vars' cons_* [weight=wtseret_], noconstant
		
		//the small perturbation from the correct initial guess seems to help
		//stata realize it has converged, without affecting the results
		if ~regexm("`varl''","hkmi") {
			matrix `allrun'_lambdainit = e(b) + J(1,`nparams' + `nlabels',0.000001)	
		}
		else {
			//this specification has some kind of divide-by-zero problem
			//when it starts too close to the correct guess
			//does not effect final results, just avoids stata error
			matrix `allrun'_lambdainit = J(1,`nparams' + `nlabels',0)	 
		}
	
		matrix all_froms = `allbetas' `all_mrets' var_means, `allrun'_lambdainit
		//J(1,`nparams'+`nlabels',0)
		
		use `temp', clear
		//matrix list wols
	
		gmm gmm_ols, onestep  vce(`setype') instruments(`all_insteqs': `vars' `lagvars') factors(`vars') assets(`allr_assets') assetclasses(`runlabels') parameters(`all_params' {means: `all_erets' `vars'} {lambda: `vars'} `all_cons') nequations(`numeq') return_prefix(eret_) winitial(identity) from(all_froms) `comsample' weights(wols3) hasderivatives `opts' rfvars(`lagvars')

		if `check_deriv' == 2 {
			
			matrix temp = e(G)
			matrix list temp
			
			gmm gmm_ols, onestep  vce(`setype') instruments(`all_insteqs': `vars' `lagvars') factors(`vars') assets(`allr_assets') assetclasses(`runlabels') parameters(`all_params' {means: `all_erets' `vars'} {lambda: `vars'} `all_cons') nequations(`numeq') return_prefix(eret_) winitial(identity) from(all_froms) `comsample' weights(wols3) `opts' rfvars(`lagvars')
			
			matrix list e(G)
			matrix temp2 = temp - e(G)
			matrix list temp2
		}
		
		
		//matrix temp = e(N_byequation)
		//local betaN = temp[1,1]
		//local meanN = temp[1,`nassets'+1]
		
		//disp "betaN: `betaN' meanN: `meanN'"
		//estadd scalar betaN = `betaN'
		//estadd scalar meanN = `meanN'
	
		estadd scalar Nassets = `alln'
		
		//local all_mape = (`all_priceerrors') / `alln'
	
		//estadd scalar MAPE = `all_mape'
	
		//test `testcmd'
		//estadd scalar PriceTest = r(p)
	
		test `testcmd_new'
		estadd scalar PriceTestNew = r(p)
	
		eststo `allrun'_xs
			
		local estnames `estnames' `allrun'_xs
		
		local mtitles `mtitles' ``allrun'_mtitle'


		outsheet `vars' `all_erets' using "./OutputInterim/MatlabInput/`varl'`allrun'`lbl_list'.csv", comma replace
		shell $matlab -nosplash -nodesktop -r "filename='`varl'`allrun'`lbl_list'.csv'; multi=1; run ./MatlabCode/KZRankTest"
	
		save `temp', replace
	
		insheet using "./OutputInterim/MatlabInput/output_`varl'`allrun'`lbl_list'.csv", clear names
	
		su pvals if names == "all", meanonly
		estadd scalar KZpval = r(mean) : `allrun'_xs
			
		use `temp', clear
		
	}
	}
	
	disp "`mtitles'"
	disp "`mtitles2'"
	
	local estnames `estnames' `estnames2'
	local mtitles `mtitles' `mtitles2'
	
	local estnames_one `estnames_one' `estnames2_one'
	local estnames_two `estnames_two' `estnames2_two'
	
	
	disp "`estnames_one'"
	disp "`estnames_two'"
	disp "`mtitles'"
	
	esttab `estnames', keep(lambda*:*)  eqlabels(none) mtitles(`mtitles') se noobs scalars("MAPE MAPE (%/mo.)" "PriceTestNew H1 p-value" "KZpval KZ p-value" "Nassets N (assets)" "betaN N (beta, mos.)" "meanN N (mean, mos.)" "converged Converged") sfmt(%8.3f %8.3f %8.3f %8.0f) indicate(Intercepts = lambda*:_cons) varwidth(16) label nostar
	
	esttab `estnames' using "./OutputFinal/gmm_results_`varl'.csv", csv replace keep(lambda*:*)  eqlabels(none) mtitles(`mtitles') se noobs scalars("MAPE MAPE (%/mo.)" "PriceTestNew H1 p-value" "KZpval KZ p-value" "Nassets N (assets)" "betaN N (beta, mos.)" "meanN N (mean, mos.)" "converged Converged") sfmt(%8.3f %8.3f %8.3f %8.0f) indicate(Intercepts = lambda*:_cons) varwidth(16) label nostar
	
	esttab `estnames' using "./OutputFinal/gmm_results_`varl'.tex", tex replace keep(lambda*:*)  eqlabels(none) mtitles(`mtitles') se noobs scalars("MAPE MAPE (%/mo.)" "PriceTestNew H1 p-value" "KZpval KZ p-value" "Nassets N (assets)" "betaN N (beta, mos.)" "meanN N (mean, mos.)" "converged Converged") sfmt(%8.3f %8.3f %8.3f %8.0f) indicate(Intercepts = lambda*:_cons) varwidth(16) label nostar
	
	if regexm("`varl'","quarter") {
		local setype `oldsetype'
	}
	
		
}

